package com.hz.wjy.service.impl;

import com.hz.wjy.helper.StringHelper;
import com.hz.wjy.mapper.UserMapper;
import com.hz.wjy.model.entiy.UserEntity;
import com.hz.wjy.model.enums.UserTypeEnum;
import com.hz.wjy.service.UserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addUser(String username, String realname, String studentId, String password, int userType) {
        // baseinfo
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername(username);
        userEntity.setRealname(realname);
        userEntity.setStudent_id(studentId);

        // create pwd
        String pwdSalt = UUID.randomUUID().toString().replace("-", "");
        String pwd = StringHelper.generateMD5(password + pwdSalt);
        userEntity.setPwd(pwd);
        userEntity.setPwd_salt(pwdSalt);
        userEntity.setUser_type(userType);
        userEntity.setPwd_error_count(0);
        userEntity.setPwd_valid_date(System.currentTimeMillis() + 7 * 24 * 3600 * 1000);
        userMapper.addUser(userEntity);
    }

    @Override
    public List<UserEntity> findAll() {
        return userMapper.findAll();
    }

    @Override
    public void deleteUser(int userId) {
        userMapper.deleteUserById(userId);
    }

    @Override
    public boolean login(String username, String password) {
        // 1，根据用户名查询对应的用户
        UserEntity userEntity = userMapper.findByUsername(username);
        if (userEntity == null) {
            return false;
        }

        // 2,若用户存在，那么获取其加密混淆因子
        String pwdSalt = userEntity.getPwd_salt();
        String pwd = userEntity.getPwd();

        // 3，根据密码明文生成密码密文，如果与数据库一致，则可登录
        String inputedPwd = StringHelper.generateMD5(password+pwdSalt);
        if (!pwd.equals(inputedPwd)) {
            return false;
        }

        // 4，将登录信息放到REDIS,SESSION放到REDIS表示登录成功，否则失败
        redisTemplate.opsForValue().set("session_" + username, userEntity.toString(), 10, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public boolean isLogined(String username) {
        return redisTemplate.opsForValue().get("session_" + username) != null;
    }


}
